package com.dmap.admin.controller.backgroundv2;

import com.dmap.admin.bo.backgroundv2.DepartmentBo;
import com.dmap.admin.constants.AdminConstant;
import com.dmap.admin.controller.backgroundv2.param.DepartmentParam;
import com.dmap.admin.controller.backgroundv2.param.DepartmentSelectParam;
import com.dmap.admin.po.Department;
import com.dmap.admin.service.backgroundv2.DepartmentService;
import com.dmap.admin.service.backgroundv2.UserV2Service;
import com.dmap.admin.units.SortList;
import com.dmap.admin.vo.backgroundv2.RecordNumAndDepartmentVo;
import com.dmap.base.constants.Constant;
import com.dmap.base.vo.BaseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * \* User: helei
 * \* Date: 16/05/18
 * \* Description:
 * \
 */
@Api(value = "个人数据服务系统-部门管理", description = "background/个人数据服务系统-部门管理")
@Controller
@RequestMapping(value = "/background/pmpd-admin-server/v2/department/")
public class DepartmentController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserV2Service userV2Service;
    @Resource
    private DepartmentService departmentService;

    @ResponseBody
    @ApiOperation(value = "新增 department",
            notes = "1. 必填： companyId, companyName, companyType, creatorId, 部门name; " +
                    "2. 返回id;")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public BaseVo insert(@RequestBody DepartmentParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getName())
                || StringUtils.isBlank(param.getCompanyId()) || !StringUtils.isNumeric(param.getCompanyId())
                || Long.valueOf(param.getCompanyId()).equals(0L) || StringUtils.isBlank(param.getCompanyName())
                || param.getCompanyType() == null || param.getCompanyType() == 0
                || StringUtils.isBlank(param.getCreatorId()) || !StringUtils.isNumeric(param.getCreatorId())
                || Long.valueOf(param.getCreatorId()).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        try {
            boolean paramIsExist = departmentService.validateNameAndCompanyIdIsExist(param.getName(), param.getCompanyId());
            if (paramIsExist) {
                baseVo.setCode(AdminConstant.RESPONSE_DEPARTMENT_EXIST_ERROR_CODE);
                baseVo.setMsg(AdminConstant.RESPONSE_DEPARTMENT_EXIST_ERROR_MSG);
                return baseVo;
            }

            Department insert = departmentService.insertDepartment(param);
            if (insert == null) {
                baseVo.setCode(Constant.RESPONSE_INSERT_ERROR_CODE);
                baseVo.setMsg(Constant.RESPONSE_INSERT_ERROR_MSG);
                return baseVo;
            }
            baseVo.setData(insert.getId().toString());
        } catch (Exception e) {
            logger.error(e.getMessage());
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "修改 department",
            notes = "1. 必填： id, companyId, companyName, companyType, creatorId, 部门name;")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public BaseVo update(@RequestBody DepartmentParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getId()) || !StringUtils.isNumeric(param.getId())
                || StringUtils.isBlank(param.getName())
                || StringUtils.isBlank(param.getCompanyId()) || !StringUtils.isNumeric(param.getCompanyId())
                || Long.valueOf(param.getId()).equals(0L) || Long.valueOf(param.getCompanyId()).equals(0L)
                || StringUtils.isBlank(param.getCompanyName()) || param.getCompanyType() == null || param.getCompanyType() == 0
                || StringUtils.isBlank(param.getCreatorId()) || !StringUtils.isNumeric(param.getCreatorId())
                || Long.valueOf(param.getCreatorId()).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        boolean success;
        try {
            success = departmentService.updateDepartment(param);
        } catch (Exception e) {
            logger.error(e.getMessage());
            baseVo.setCode(AdminConstant.RESPONSE_DEPARTMENT_EXIST_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_DEPARTMENT_EXIST_ERROR_MSG);
            return baseVo;
        }
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_UPDATE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_UPDATE_ERROR_MSG);
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "批量删除 department",
            notes = "1. 必填： id;" +
                    "2. 删除功能只有当部门成员为0时，才可以删除;")
    @RequestMapping(value = "delete/deleteByIdList", method = RequestMethod.POST)
    public BaseVo deleteByIdList(@RequestBody List<String> list) {
        BaseVo baseVo = new BaseVo();
        if (CollectionUtils.isEmpty(list)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        List<Long> deleteList = new ArrayList<>();
        for (String id : list) {
            if (StringUtils.isNotBlank(id) && StringUtils.isNumeric(id) && !Long.valueOf(id).equals(0L)) {
                int memberNum = userV2Service.countByDepartmentId(Long.valueOf(id));
                if (memberNum == 0) {
                    deleteList.add(Long.valueOf(id));
                } else {
                    baseVo.setCode(AdminConstant.RESPONSE_DELETE_MEMBER_NUM_NOT_0_ERROR_CODE);
                    baseVo.setMsg(id + AdminConstant.RESPONSE_DELETE_MEMBER_NUM_NOT_0_ERROR_MSG);
                    return baseVo;
                }
            }
        }
        boolean success = departmentService.deleteByIdList(deleteList);
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_DELETE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_DELETE_ERROR_MSG);
        }
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据部门id查询部门", notes = "1. 必填： id;")
    @RequestMapping(value = "select/selectById", method = RequestMethod.GET)
    public BaseVo selectById(@RequestParam String id) {
        BaseVo baseVo = new BaseVo();
        if (StringUtils.isBlank(id) || !StringUtils.isNumeric(id) || Long.valueOf(id).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        Department department = departmentService.selectById(Long.valueOf(id));
        List<DepartmentBo> boList = new ArrayList<>();
        if (department != null) {
            DepartmentBo bo = new DepartmentBo(department);
            int num = userV2Service.countByDepartmentId(department.getId());
            if (num > 0) {
                bo.setMemberNum(num);
            }
            boList.add(bo);
        }
        RecordNumAndDepartmentVo recordNumAndDepartmentVo = new RecordNumAndDepartmentVo(1, boList);
        baseVo.setData(recordNumAndDepartmentVo);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据参数查询department列表，和模糊查询、排序是一个接口",
            notes = "1. 必填： companyId, userType;" +
                    "2. 必填：pageIndex(>=1), pageSize(>=1);" +
                    "3. 返回department列表;")
    @RequestMapping(value = "select/selectByExample", method = RequestMethod.POST)
    public BaseVo selectByExample(@RequestBody DepartmentSelectParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getCompanyId()) || !StringUtils.isNumeric(param.getCompanyId())
                || Long.valueOf(param.getCompanyId()).equals(0L)
                || (param.getUserType() != AdminConstant.USER_TYPE_COMPANY_ADMIN && param.getUserType() != AdminConstant.USER_TYPE_DEPARTMENT_ADMIN)
                || param.getPageIndex() == null || param.getPageSize() == null
                || param.getPageIndex() < 1 || param.getPageSize() < 1) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        if (param.getUserType() != AdminConstant.USER_TYPE_COMPANY_ADMIN
                && (StringUtils.isBlank(param.getDepartmentId()) || !StringUtils.isNumeric(param.getDepartmentId())
                || Long.valueOf(param.getDepartmentId()).equals(0L))) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        int recordNum = departmentService.countByDepartmentSelectParam(param);
        List<DepartmentBo> boList = new ArrayList<>();
        if (recordNum > 0) {
            List<Department> list = departmentService.selectByDepartmentSelectParam(param);
            for (Department department : list) {
                if (department != null) {
                    DepartmentBo bo = new DepartmentBo(department);
                    int num = userV2Service.countByDepartmentId(department.getId());
                    if (num > 0) {
                        bo.setMemberNum(num);
                    }
                    boList.add(bo);
                }
            }
        }
        if (param.getSortField() != null && CollectionUtils.isNotEmpty(boList) && boList.size() > 1
                && param.getSortField().equalsIgnoreCase(AdminConstant.SORT_BY_MEMBER_NUM)) {
            SortList<DepartmentBo> sortList = new SortList<>();
            if (param.getOrder() == AdminConstant.ORDER_BY_ASC) {
                sortList.sortByMethod(boList, "getMemberNum", false);
            } else if (param.getOrder() == AdminConstant.ORDER_BY_DESC) {
                sortList.sortByMethod(boList, "getMemberNum", true);
            }
        }
        RecordNumAndDepartmentVo recordNumAndDepartmentVo = new RecordNumAndDepartmentVo(recordNum, boList);
        baseVo.setData(recordNumAndDepartmentVo);
        return baseVo;
    }

}